from flask import request, jsonify
from routes import app
from services.gep_service import GepService

# from flask_login import login_required

# 创建 GepService 实例
gep_service = GepService()


@app.route("/gep_parameters", methods=['GET', 'POST'])
def gep_parameters():
    if request.method == 'POST':  # 添加新参数
        data = request.json  # 获取 JSON 格式的请求数据
        try:
            gep_parameter = gep_service.add_gep_parameter(data)  # 调用服务添加参数
            return jsonify(gep_parameter.to_dict()), 201  # 返回创建的资源和状态码
        except ValueError as e:  # 捕获值错误异常
            return jsonify({'error': str(e)}), 400  # 返回错误信息和状态码
    elif request.method == 'GET':  # 获取所有参数
        gep_parameters = gep_service.get_all_gep_parameters()  # 获取所有参数
        return jsonify([param.to_dict() for param in gep_parameters]), 200  # 返回参数列表和状态码


@app.route("/gep_parameters_by_id/<int:id>", methods=['GET', 'PUT', 'DELETE'])
def gep_parameter_by_id(id):
    if request.method == 'GET':  # 获取指定 ID 的参数
        try:
            gep_parameter = gep_service.get_gep_parameter(id)  # 获取指定 ID 的参数
            return jsonify(gep_parameter.to_dict()), 200  # 返回参数和状态码
        except ValueError as e:  # 捕获值错误异常
            return jsonify({'error': str(e)}), 404  # 返回错误信息和状态码
    elif request.method == 'PUT':  # 更新指定 ID 的参数
        data = request.json  # 获取 JSON 格式的请求数据
        try:
            updated_parameter = gep_service.update_gep_parameter(id, data)  # 更新参数
            return jsonify(updated_parameter.to_dict()), 200  # 返回更新后的参数和状态码
        except ValueError as e:  # 捕获值错误异常
            return jsonify({'error': str(e)}), 400  # 返回错误信息和状态码
    elif request.method == 'DELETE':  # 删除指定 ID 的参数
        try:
            if gep_service.delete_gep_parameter(id):  # 删除参数
                return jsonify({'message': 'Deleted successfully'}), 200  # 返回成功消息和状态码
            else:
                return jsonify({'error': 'Not found'}), 404  # 返回未找到错误和状态码
        except ValueError as e:  # 捕获值错误异常
            return jsonify({'error': str(e)}), 400  # 返回错误信息和状态码


@app.route("/gep_parameters/query", methods=["GET"])
def query_gep_parameter():
    year = request.args.get("year", type=int)
    gep_city = request.args.get("gepCity")
    gep_district = request.args.get("gepDistrict")
    gep_town = request.args.get("gepTown")

    if not all([year, gep_city, gep_district, gep_town]):
        return jsonify({"error": "Missing required parameters"}), 400

    gep_id = gep_service.get_gep_parameter_id_by_fields(year, gep_city, gep_district, gep_town)

    if gep_id is not None:
        return jsonify({"id": gep_id}), 200
    else:
        return jsonify({"error": "Record not found"}), 404


@app.route("/gep_parameters_by_fields/<int:year>/<string:gepCity>/<string:gepDistrict>/<string:gepTown>",
           methods=['GET', 'PUT', 'DELETE'])
def gep_parameter_by_fields(year, gepCity, gepDistrict, gepTown):
    if request.method == 'GET':
        print("gep_parameter_by_fields", year, gepCity, gepDistrict, gepTown)
        record = gep_service.get_gep_parameter_by_fields(year, gepCity, gepDistrict, gepTown)
        if record:
            return jsonify(record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404

    elif request.method == 'PUT':
        data = request.json
        print("gep_parameters_by_fields data", data)
        # 预处理数据，将 None 值转换为 0
        numeric_fields = ['inAgricultural', 'inAnimalHusbandry', 'inAverageIncome', 'inEcologicalEnergy', 'inWaterResources'
            , 'inElectricityPrice', 'inFishery'
            , 'inHousePrice', 'inHotelRooms'
            , 'inHousingAreaPerCapita', 'inLeisureTime'
            , 'inForestry', 'inLocalWaterPrice'
            , 'inOccupancyRate', 'inProtectedArea'
            , 'inProtectedCost', 'inRoomPrice'
            , 'inTourismRevenue', 'inUrbanPopulation'
            , 'inNoiseCost', 'inNoiseReductionAmount']  # 根据实际模型字段调整
        for field in numeric_fields:
            if field in data and (data[field] is None or data[field] == ''):
                data[field] = 0
        print("gep_parameters_by_fields numeric_fields data", data)
        updated_record = gep_service.update_gep_parameter_by_fields(year, gepCity, gepDistrict, gepTown, data)
        if updated_record:
            return jsonify(updated_record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found or failed to update'}), 404

    elif request.method == 'DELETE':
        deleted = gep_service.delete_gep_parameter_by_fields(year, gepCity, gepDistrict, gepTown)
        if deleted:
            return jsonify({'message': 'Deleted successfully'}), 200
        else:
            return jsonify({'error': 'Not found'}), 404


# GEP Result Routes
@app.route("/gep_results", methods=['GET', 'POST'])
# @login_required
def gep_results():
    if request.method == 'POST':  # 添加新结果
        data = request.json  # 获取 JSON 格式的请求数据
        gep_result = gep_service.add_gep_result(data)  # 调用服务添加结果
        return jsonify(gep_result.to_dict()), 201  # 返回创建的资源和状态码
    elif request.method == 'GET':  # 获取所有结果
        gep_results = gep_service.get_all_gep_results()  # 获取所有结果
        return jsonify([result.to_dict() for result in gep_results]), 200  # 返回结果列表和状态码


@app.route("/gep_results_by_id/<int:id>", methods=['GET', 'PUT', 'DELETE'])
# @login_required
def gep_result_by_id(id):
    if request.method == 'GET':  # 获取指定 ID 的结果
        gep_result = gep_service.get_gep_result(id)  # 获取指定 ID 的结果
        if gep_result:
            return jsonify(gep_result.to_dict()), 200  # 返回结果和状态码
        else:
            return jsonify({'error': 'Not found'}), 404  # 返回未找到错误和状态码
    elif request.method == 'PUT':  # 更新指定 ID 的结果
        data = request.json  # 获取 JSON 格式的请求数据
        updated_result = gep_service.update_gep_result(id, data)  # 更新结果
        if updated_result:
            return jsonify(updated_result.to_dict()), 200  # 返回更新后的结果和状态码
        else:
            return jsonify({'error': 'Not found'}), 404  # 返回未找到错误和状态码
    elif request.method == 'DELETE':  # 删除指定 ID 的结果
        if gep_service.delete_gep_result(id):  # 删除结果
            return jsonify({'message': 'Deleted successfully'}), 200  # 返回成功消息和状态码
        else:
            return jsonify({'error': 'Not found'}), 404  # 返回未找到错误和状态码


@app.route("/gep_results/query", methods=["GET"])
def query_gep_result():
    year = request.args.get("year", type=int)
    gep_city = request.args.get("gepCity")
    gep_district = request.args.get("gepDistrict")
    gep_town = request.args.get("gepTown")

    if not all([year, gep_city, gep_district, gep_town]):
        return jsonify({"error": "Missing required parameters"}), 400

    result_id = gep_service.get_gep_result_id_by_fields(year, gep_city, gep_district, gep_town)

    if result_id is not None:
        return jsonify({"id": result_id}), 200
    else:
        return jsonify({"error": "Record not found"}), 404


# 推荐 URL 格式：/gep_parameter_by_fields/2023/上饶市/铅山县/河口镇
@app.route("/gep_results_by_fields/<int:year>/<string:gepCity>/<string:gepDistrict>/<string:gepTown>",
           methods=['GET', 'PUT', 'DELETE'])
def gep_result_by_fields(year, gepCity, gepDistrict, gepTown):
    if request.method == 'GET':
        record = gep_service.get_gep_result_by_fields(year, gepCity, gepDistrict, gepTown)
        if record:
            return jsonify(record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found'}), 404

    elif request.method == 'PUT':
        data = request.json
        print("gep_results_by_fields data", data)
        # 预处理数据，将 None 值转换为 0
        numeric_fields = ['cleanEnergyValue', 'gepResult', 'landscapeAppreciationValue', 'leisureRecreationValue'
            , 'materialSupplyValue'
            , 'tourismHealthValue'
            , 'waterResourcesValue']  # 根据实际模型字段调整
        for field in numeric_fields:
            if field in data and (data[field] is None or data[field] == ''):
                data[field] = 0
        print("gep_results_by_fields numeric_fields data", data)
        updated_record = gep_service.update_gep_result_by_fields(year, gepCity, gepDistrict, gepTown, data)
        if updated_record:
            return jsonify(updated_record.to_dict()), 200
        else:
            return jsonify({'error': 'Not found or failed to update'}), 404

    elif request.method == 'DELETE':
        deleted = gep_service.delete_gep_result_by_fields(year, gepCity, gepDistrict, gepTown)
        if deleted:
            return jsonify({'message': 'Deleted successfully'}), 200
        else:
            return jsonify({'error': 'Not found'}), 404
